<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发起请求的团队" prop="teamId">
          <el-select
            v-model="queryParams.teamId"
            placeholder="请选择发起请求的团队"
            clearable
          >
            <el-option
              v-for="team in teamOptions"
              :key="team.teamId"
              :label="team.teamName"
              :value="team.teamId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发起请求的装备名称" prop="equipmentId">
          <el-select
            v-model="queryParams.equipmentId"
            placeholder="请输入请求的装备名称"
            clearable
          >
            <el-option
              v-for="equipment in equipmentOptions"
              :key="equipment.equipmentId"
              :label="equipment.equipmentName"
              :value="equipment.equipmentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请求的物资名称" prop="materialId">
          <el-select
            v-model="queryParams.materialId"
            placeholder="请输入请求的物资名称"
            clearable
          >
            <el-option
              v-for="material in materialOptions"
              :key="material.supplyid"
              :label="material.supplyname"
              :value="material.supplyid"
            />
          </el-select>
        </el-form-item>
      
      <el-form-item label="状态" prop="statusId">
        <el-input
          v-model="queryParams.statusId"
          placeholder="请输入状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['resourcerequest:resourcerequest:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['resourcerequest:resourcerequest:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['resourcerequest:resourcerequest:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['resourcerequest:resourcerequest:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resourcerequestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="requestId" />
      <el-table-column label="发起请求的队伍名称" align="center" prop="teamName" />
      <el-table-column label="请求的装备名称" align="center" prop="equipmentName" />
      <el-table-column label="请求的装备数量" align="center" prop="equipmentQuantity" />
      <el-table-column label="请求的物资名称" align="center" prop="materialName" />
      <el-table-column label="请求的物资数量" align="center" prop="materialQuantity" />
      <el-table-column label="请求原因" align="center" prop="requestReason" />
      <el-table-column label="请求发起时间" align="center" prop="requestTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.requestTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="期望获取时间" align="center" prop="expectedDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approver" />
      <el-table-column label="审批时间" align="center" prop="approvalTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvalTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批备注" align="center" prop="approvalRemark" />
      <el-table-column label="审批结果" align="center" prop="statusLabel" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['resourcerequest:resourcerequest:edit']"
          >修改</el-button>
           <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAuth(scope.row)"
            v-hasPermi="['resourcerequest:resourcerequest:auth']"
          >审批</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resourcerequest:resourcerequest:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资源请求对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 团队编号改为下拉框 -->
        <el-form-item label="发起请求的队伍编号" prop="teamId">
          <el-select
            v-model="form.teamId"
            placeholder="请选择队伍编号"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="team in teamOptions"
              :key="team.teamId"
              :label="team.teamName"  
              :value="team.teamId" 
            />
          </el-select>
        </el-form-item>
        <!-- 装备ID改为下拉框 -->
        <el-form-item label="请求的装备" prop="equipmentId">
          <el-select
            v-model="form.equipmentId"
            placeholder="请选择装备"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="equipment in equipmentOptions"
              :key="equipment.id"  
              :label="equipment.equipmentName"  
              :value="equipment.id" 
            />
          </el-select>
        </el-form-item>
       <el-form-item label="请求的装备数量" prop="equipmentQuantity">
          <el-input-number
            v-model.number="form.equipmentQuantity"
            :min="0"
            :max="9999" 
            placeholder="请输入请求的装备数量"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="请求的物资" prop="materialId">
          <el-select
            v-model="form.materialId"
            placeholder="请选择物资"
            clearable
            style="width: 100%"
            @change="handleMaterialChange"
          >
          <el-option
            v-for="material in materialOptions"
            :key="material.supplyid"  
            :label="material.supplyname"  
            :value="material.supplyid"  
          />
          </el-select>
        </el-form-item>
        <el-form-item label="请求的物资数量" prop="materialQuantity">
          <el-input-number
            v-model.number="form.materialQuantity"
            :min="0"
            :max="9999" 
            @change="handleMaterialQuantityChange"
            placeholder="请输入请求的物资数量"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="请求原因" prop="requestReason">
          <el-input v-model="form.requestReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="请求发起时间" prop="requestTime">
          <el-date-picker clearable
            v-model="form.requestTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择请求发起时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="期望获取时间" prop="expectedDate">
          <el-date-picker clearable
            v-model="form.expectedDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择期望获取时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改资源请求对话框 -->
    <el-dialog :title="title" :visible.sync="openauth" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">        
        <el-form-item label="审批人" prop="approver">
          <el-input v-model="form.approver" placeholder="请输入审批人" />
        </el-form-item>
        <el-form-item label="审批时间" prop="approvalTime">
          <el-date-picker clearable
            v-model="form.approvalTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择审批时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批意见" prop="approvalRemark">
          <el-input v-model="form.approvalRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="审批结果" prop="statusId">
          <el-select v-model="form.statusId" placeholder="请选择审批结果"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateauth">确 定</el-button>
        <el-button @click="cancelauth">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listResourcerequest, getResourcerequest, delResourcerequest, authResourcerequest, addResourcerequest, updateResourcerequest } from "@/api/resourcerequest/resourcerequest"
import { listTeam } from "@/api/team/team"; // 新增：导入团队列表接口
import { listAvailableEquipments } from "@/api/equipment/equipment"; // 替换原 listALLEquipment
import { listALLMaterial } from "@/api/materialtable/materialtable"; // 新增：导入物资列表接口

export default {
  name: "Resourcerequest",
  data() {
    return {
      teamOptions: [],// 新增：团队下拉框选项
      equipmentOptions: [],// 新增：装备下拉框数据
      materialOptions: [],// 新增：物资下拉框数据
      materialStockMap: {}, // 存储物资 ID -> 库存的映射
      statusOptions: [], 
      addflag:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资源请求表格数据
      resourcerequestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      openauth: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamId: null,
        equipmentId: null,
        materialId: null,
        statusId: null
      },
      // 表单参数
      form: {
        materialId: null,
        materialQuantity: null
      },
          // 表单校验
      rules: {
        teamId: [
          { required: true, message: "发起请求的团队编号不能为空", trigger: "blur" }
        ],
        // // 物资数量校验规则
        // materialQuantity: [
        //   { 
        //     validator: this.validateMaterialQuantity, 
        //     trigger: 'blur' 
        //   }
        // ]
      }
    }
  },
  created() {
    this.loadTeamOptions(); // 新增：页面加载时获取团队列表
    this.loadEquipmentOptions(); // 新增：加载装备数据
    this.loadMaterialOptions(); // 新增：加载物资数据
    this.getDicts("request_status").then((res)=>{this.statusOptions=res.data;
    });
    this.getList();
  },
  methods: {
    /** 新增：加载团队下拉框数据 */
    loadTeamOptions() {
      listTeam().then(response => {
        this.teamOptions = response.rows;
      });
    },

     /** 新增：加载装备下拉框数据 */
    loadEquipmentOptions() {
      listAvailableEquipments().then(response => {
        this.equipmentOptions = response.data || []; 
      });
    },

     /** 新增：加载物资下拉框数据 */
    loadMaterialOptions() {
      listALLMaterial().then(response => {
        this.materialOptions = response.data || []; 
        // 构建 {物资ID: 库存} 的映射
        this.materialStockMap = {};
        this.materialOptions.forEach(item => {
          this.materialStockMap[item.supplyid] = item.currentStock; 
          });
      });
    },
     // 选中物资时，重置数量校验
    handleMaterialChange() {
      this.$refs['form'].validateField('materialQuantity'); 
    },

    validateMaterialQuantity(rule, value, callback) {
      if (!this.form.materialId) {
        callback(); 
        return;
      }
      const stock = this.materialStockMap[this.form.materialId];
      if (value > stock) {
        callback(new Error(`请求数量不能超过当前库存（库存：${stock}）`));
      } else {
        callback();
      }
      },

    /** 查询资源请求列表 */
    getList() {
      this.loading = true
      listResourcerequest(this.queryParams).then(response => {
        this.resourcerequestList = response.rows
         // 关键：遍历请求列表，匹配团队名称
        this.resourcerequestList.forEach(request => {
          const team = this.teamOptions.find(team => team.teamId === request.teamId);
          request.teamName = team ? team.teamName : '未知团队' ;
          // 新增装备名称匹配逻辑
          const equipment = this.equipmentOptions.find(equip => equip.id === request.equipmentId);
          request.equipmentName = equipment ? equipment.equipmentName : '无'; 
          // 新增：物资名称匹配
          const material = this.materialOptions.find(mat => mat.supplyid === request.materialId);
          request.materialName = material ? material.supplyname : '无';
          
          const statusDict = this.statusOptions.find(
          dict => dict.dictValue === String(request.statusId) 
      );
      request.statusLabel = statusDict ? statusDict.dictLabel : '待审批';
        })
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancelauth() {
      this.openauth = false
      this.reset()
    },
    
    // 表单重置
    reset() {
      this.form = {
        requestId: null,
        teamId: null,
        equipmentId: null,
        equipmentQuantity: null,
        materialId: null,
        materialQuantity: null,
        requestReason: null,
        requestTime: null,
        expectedDate: null,
        approver: null,
        approvalTime: null,
        approvalRemark: null,
        statusId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.requestId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.addflag = true
      this.open = true
      this.title = "添加资源请求"
    },
    
   
    /**审批操作 */
    handleAuth(row) {
      this.reset()
      const requestId = row.requestId || this.ids
      getResourcerequest(requestId).then(response => {
        this.form = response.data
        this.openauth = true
        this.title = "审核资源请求"
      })
    }, 
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const requestId = row.requestId || this.ids
      getResourcerequest(requestId).then(response => {
        this.form = response.data
        this.addflag =false
        this.open = true
        this.title = "修改资源请求"
      })
    },
    //updateauth
/** 保存审核意见 */
    updateauth() {
     authResourcerequest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.openauth = false
              this.getList()
            })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.addflag) {
            authResourcerequest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addResourcerequest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const requestIds = row.requestId || this.ids
      this.$modal.confirm('是否确认删除资源请求编号为"' + requestIds + '"的数据项？').then(function() {
        return delResourcerequest(requestIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('resourcerequest/resourcerequest/export', {
        ...this.queryParams
      }, `resourcerequest_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
